import React, { useCallback, useMemo } from 'react'
import { Descriptions as AntdDescriptions, Space, Tag } from 'antd'
import { useT } from '@designable/event-system'
import { Button } from '../Button'
import { createSchemaField, useFieldSchema, useForm } from '@formily/react'
import { observer } from '@formily/reactive-react'
import { CreateExecutor } from '@designable/event-system'

export interface DescriptionsProps {
  title?: string
  className?: string
  style?: React.CSSProperties
  buttons?: any[]
  value?: any
  bordered?: boolean
  column?: number | Partial<Record<string, number>>
  size?: 'default' | 'middle' | 'small'
  layout?: 'horizontal' | 'vertical'
  [key: string]: any
}

// 状态颜色映射
const statusColor: any = {
  finish: 'success',
  sales_finish: 'success',
  cancel: 'error',
  canceling: 'processing',
  using: 'processing',
  wait_pay: 'processing',
  wait_hand: 'processing',
  wait_settle: 'processing',
  wait_use: 'processing',
  wait_audit: 'processing',
  wait_receive: 'processing',
  wait_deliver: 'processing',
  sales_canceling: 'processing',
  appointment_failed: 'error',
  deliver: 'success',
}

const Text: React.FC<{
  value?: string
  nameKey?: string
  children?: React.ReactNode
}> = observer((props) => {
  const form = useForm()
  const formValues = form.getFormState().values

  // 根据 nameKey 获取对应的值
  const getValueByKey = (key?: string) => {
    if (!key) return props.value || props.children

    // 支持嵌套属性访问，如 'user.name'
    const keys = key.split('.')
    let value = formValues

    for (const k of keys) {
      if (value && typeof value === 'object' && k in value) {
        value = value[k]
      } else {
        return props.value || props.children // 如果找不到，返回默认值
      }
    }

    return value
  }

  const content = getValueByKey(props.nameKey)

  return <div>{content}</div>
})

// 工具函数
const safeExecute = (executor: any, context: any) => {
  try {
    return CreateExecutor(executor)(context)
  } catch (error) {
    console.error('执行表达式失败:', error)
  }
}
export interface AntdDescriptionsWrapperProps {
  buttons?: any[]
  bordered?: boolean
  column?: number | Partial<Record<string, number>>
  size?: 'default' | 'middle' | 'small'
  layout?: 'horizontal' | 'vertical'
  children?: React.ReactNode
  [key: string]: any
}

export const AntdDescriptionsWrapper: React.FC<AntdDescriptionsWrapperProps> =
  observer(
    ({
      buttons = [],
      bordered = false,
      column = 3,
      size = 'default',
      layout = 'horizontal',
      children,
      title,
      ...props
    }) => {
      const $t = useT()
      const form = useForm()
      const formValues = form.getFormState().values

      // 从表单中获取 orderNo 值作为标题
      const orderNo = formValues?.orderNo || title
      const orderStatus = formValues?.orderStatus || 'wait_hand'
      const orderStatusName = formValues?.orderStatusName || '订单状态'
      const isSubOrderNo = formValues?.isSubOrderNo || false

      // 渲染标题
      const renderTitle = () => {
        return (
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              fontSize: 20,
              marginBottom: 20,
            }}
          >
            {$t('订单编号')}：{orderNo}
            <div style={{ marginLeft: 10 }}>
              {isSubOrderNo && (
                <Tag style={{ fontSize: 14 }}>{$t('子订单')}</Tag>
              )}
              <Tag style={{ fontSize: 14 }} color={statusColor[orderStatus]}>
                {orderStatusName}
              </Tag>
            </div>
          </div>
        )
      }

      // 渲染 extra 按钮列表
      const renderExtra = useCallback(() => {
        if (!buttons || buttons.length === 0) return null
        const visibleButtons = buttons.filter((item: any) => {
          if (!item.visible) return true
          return safeExecute(item.visible, { values: formValues }) !== false
        })
        return (
          <Space>
            {visibleButtons.map((item: any, index: number) => (
              <Button key={index} {...item} />
            ))}
          </Space>
        )
      }, [buttons, formValues])

      return (
        <AntdDescriptions
          title={renderTitle()}
          extra={renderExtra()}
          bordered={bordered}
          column={column}
          size={size}
          layout={layout}
          {...props}
        >
          {children}
        </AntdDescriptions>
      )
    }
  )

export const Descriptions: React.FC<DescriptionsProps> = observer(
  ({ className, style, ...props }) => {
    const $t = useT()
    const fieldSchemaProperties = useFieldSchema().properties || {}
    const form = useForm()
    const formValues = form.getFormState().values

    const items = (Object.values(fieldSchemaProperties) || [])
      .map((item) => {
        const schema = {
          ...item,
          type: 'void',
          'x-component': 'Text',
        }

        const componentProps = item['x-component-props'] || {}
        const visibleExpression = componentProps.visibleExpression
        if (visibleExpression) {
          try {
            componentProps.visible =
              CreateExecutor(visibleExpression)(formValues)
          } catch (error) {
            console.warn('表达式执行失败:', error)
            componentProps.visible = true // 默认显示
          }
        } else {
          componentProps.visible = true
        }

        return {
          ...componentProps,
          schema: {
            type: 'void',
            properties: {
              [item['x-designable-id']]: schema,
            },
          },
        }
      })
      .filter((item) => item.visible)

    const SchemaField = useMemo(() => {
      return createSchemaField({
        components: {
          Text,
        },
        scope: { $t },
      })
    }, [$t])

    return (
      <div className={className} style={style}>
        <AntdDescriptionsWrapper {...props}>
          {items.map((item, index) => (
            <AntdDescriptions.Item
              key={item.key || index}
              label={item.label}
              span={item.span}
            >
              {item.schema ? (
                <SchemaField schema={item.schema} />
              ) : (
                <Text value="后备文本" />
              )}
            </AntdDescriptions.Item>
          ))}
        </AntdDescriptionsWrapper>
      </div>
    )
  }
)
